<template>
  <div>
    <!-- 搜索框 -->
    <a-row :gutter="16" style="margin-bottom: 16px;">
      <a-row :gutter="16">
        <a-col :span="7">
          <a-input
              v-model="search.username"
              placeholder="请输入管理员账号"
              addon-before="管理员账号"/>
        </a-col>
        <a-col :span="7">
          <a-input
              v-model="search.nickname"
              placeholder="请输入管理员名称"
              addon-before="管理员名称"/>
        </a-col>
        <a-col :span="6">
          <a-select v-model="search.roleIds" placeholder="管理员角色" style="width: 100%">
            <a-select-option value="全部">全部</a-select-option>
            <a-select-option value="管理员">管理员</a-select-option>
            <a-select-option value="超级管理员">超级管理员</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="2">
          <a-button type="primary" @click="handleSearch" style="left: 20px">查询</a-button>
        </a-col>
        <a-col :span="2">
          <a-button @click="handleReset" style="right: 20px">重置</a-button>
        </a-col>
      </a-row>
    </a-row>

    <!-- 新增按钮 -->
    <a-button type="primary" style="margin-top: 16px;" @click="handleAdd">新增</a-button>

    <!-- 数据表格 -->
    <a-table :columns="columns" :data-source="pagedData" :pagination="false" style="margin-top: 16px;">
      <template slot="avatar" slot-scope="record">
        <a-avatar :src="record.avatar || defaultAvatar" :size="64" @error="handleAvatarError"/>
      </template>
      <template slot="disable" slot-scope="record">
        <span v-if="record && record.disable !== undefined && record.disable !== null"
              :style="{
        color: record.disable === 0 ? '#67c23a' :
              record.disable === 1 ? '#ff4d4f' :
              '#000000',
        background: record.disable === 1 ? '#fef0f0' : '#f0f9eb',
        padding: '5px 10px'
      }">
      {{ record.disable === 0 ? '启用' : record.disable === 1 ? '禁用' : '未知' }}
    </span>
      </template>
      <template slot="Controls" slot-scope="record">
        <a-button type="link" @click="handleEdit(record)">编辑</a-button>
        <a-popconfirm title="确定删除此管理员吗？" @confirm="() => handleDelete(record)">
          <a-button type="link" danger>删除</a-button>
        </a-popconfirm>
      </template>
    </a-table>


    <!-- 分页和数据统计 -->
    <div
        style="margin-top: 16px; margin-left: 80%; display: flex; justify-content: space-between; align-items: center; font-size: 14px; color: #666;">
      <div>
        <span>共 {{ filteredData.length }} 条数据</span>
        <span style="margin-left: 10px;">每页显示 {{ pageSize }} 条</span>
        <span style="margin-left: 10px;">当前第 {{ currentPage }} 页</span>
      </div>
    </div>

    <a-pagination
        :current="currentPage"
        :total="filteredData.length"
        :page-size="pageSize"
        @change="handlePageChange"
        style=" text-align: center; width: 100%;"
    />

    <!-- 新增/编辑弹窗 -->
    <a-modal
        v-model="isModalVisible"
        :title="isEditing ? '编辑管理员' : '新增管理员'"
        @ok="handleSave"
        @cancel="handleCancel"
        :destroy-on-close="true"
    >
      <a-form :model="form" label-col="{ span: 5 }" wrapper-col="{ span: 16 }">
        <a-form-item label="管理员账号">
          <a-input v-model="form.username" :disabled="isEditing"/>
        </a-form-item>
        <a-form-item v-if="!isEditing" label="管理员密码">
          <a-input v-model="form.password"/>
        </a-form-item>
        <a-form-item v-if="isEditing" label="管理员名称">
          <a-input v-model="form.nickname"/>
        </a-form-item>
        <a-form-item v-if="isEditing" label="管理员角色">
          <a-select v-model="form.roleids">
            <a-select-option value="管理员">管理员</a-select-option>
            <a-select-option value="超级管理员">超级管理员</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="isEditing" label="部门">
          <a-input v-model="form.deptIds"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import {METHOD, request} from "@/utils/request";

export default {
  data() {
    return {
      defaultAvatar: `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/default_avatar.png`,
      search: {
        username: '',
        nickname: '',
        roleIds: '全部',
      },
      columns: [
        {title: 'ID', dataIndex: 'id', key: 'id'},
        {title: '头像', dataIndex: 'avatar', key: 'avatar', scopedSlots: {customRender: 'avatar'}},
        {title: '管理员账号', dataIndex: 'username', key: 'username'},
        {title: '管理员名称', dataIndex: 'nickname', key: 'nickname'},
        {title: '管理员角色', dataIndex: 'roleids', key: 'roleids'},
        {title: '部门', dataIndex: 'deptIds', key: 'deptIds'},
        {title: '创建时间', dataIndex: 'createTime', key: 'createTime'},
        {title: '最近登录时间', dataIndex: 'lastLoginTime', key: 'lastLoginTime'},
        {title: '最近登录IP', dataIndex: 'lastLoginIp', key: 'lastLoginIp'},
        {title: '状态', key: 'disable', scopedSlots: {customRender: 'disable'}},
        {title: '操作', key: 'Controls', scopedSlots: {customRender: 'Controls'}},
      ],
      data: [
        // {
        //   id: 1,
        //   adminAccount: 'admin001',
        //   adminName: '张三',
        //   adminRole: '超级管理员',
        //   status: '禁用',
        //   avatar: '',
        //   Department: '信息部',
        //   CreationTime: '2024-11-25 10:03:16',
        //   lastlogintime: '2024-12-18 15:17:50',
        //   LastloginIP: '47.130.84.194'
        // },
        // {
        //   id: 2,
        //   adminAccount: 'admin002',
        //   adminName: '李四',
        //   adminRole: '管理员',
        //   status: '禁用',
        //   avatar: '',
        //   Department: '技术部',
        //   CreationTime: '2024-11-26 11:05:20',
        //   lastlogintime: '2024-12-19 12:30:10',
        //   LastloginIP: '47.130.84.195'
        // },
        // {
        //   id: 3,
        //   adminAccount: 'admin003',
        //   adminName: '王五',
        //   adminRole: '管理员',
        //   status: '启用',
        //   avatar: '',
        //   Department: '市场部',
        //   CreationTime: '2024-12-01 09:12:12',
        //   lastlogintime: '2024-12-19 14:00:00',
        //   LastloginIP: '47.130.84.196'
        // },
        // {
        //   id: 4,
        //   adminAccount: 'admin004',
        //   adminName: '赵六',
        //   adminRole: '普通管理员',
        //   status: '启用',
        //   avatar: '',
        //   Department: '运营部',
        //   CreationTime: '2024-12-02 08:22:45',
        //   lastlogintime: '2024-12-19 13:45:30',
        //   LastloginIP: '47.130.84.197'
        // },
        // {
        //   id: 5,
        //   adminAccount: 'admin005',
        //   adminName: '孙七',
        //   adminRole: '超级管理员',
        //   status: '禁用',
        //   avatar: '',
        //   Department: '财务部',
        //   CreationTime: '2024-12-03 15:33:55',
        //   lastlogintime: '2024-12-19 16:12:20',
        //   LastloginIP: '47.130.84.198'
        // },
        // {
        //   id: 6,
        //   adminAccount: 'admin006',
        //   adminName: '周八',
        //   adminRole: '管理员',
        //   status: '启用',
        //   avatar: '',
        //   Department: '销售部',
        //   CreationTime: '2024-12-05 11:45:17',
        //   lastlogintime: '2024-12-19 17:22:00',
        //   LastloginIP: '47.130.84.199'
        // },
      ],
      currentPage: 1,
      pageSize: 10,
      isModalVisible: false,
      isEditing: false,
      form: {
        username: '',
        password: '',
        nickname: '',
        roleIds: '管理员',
        deptIds: ''
      },
    };
  },
  mounted() {
    this.fetchData();  // 调用 fetchData 获取数据
    console.log("用户数据：" + this.data)
  },
  computed: {
    filteredData() {
      const {username, nickname, roleIds} = this.search;
      return this.data.filter(item => {
        return (
            (!username || item.username.includes(username)) &&
            (!nickname || item.nickname.includes(nickname)) &&
            (roleIds === '全部' || item.roleIds === roleIds)
        );
      });
    },
    pagedData() {
      const startIndex = (this.currentPage - 1) * this.pageSize;
      return this.filteredData.slice(startIndex, startIndex + this.pageSize);
    }
  },
  methods: {
    handleAvatarError(event) {
      event.target.src = this.defaultAvatar;
    },
    handleSearch() {
      // 在此更新 search 数据，filteredData 会自动更新
      this.currentPage = 1; // 重置为第一页
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleReset() {
      this.search = {
        username: '',
        nickName: '',
        roleids: '全部',
      };
      this.currentPage = 1; // 重置为第一页
    },
    handleAdd() {
      this.isEditing = false;
      this.form = {
        id: null,
        adminAccount: '',
        adminName: '',
        adminRole: '管理员',
        Department: '',
        status: true,
      };
      this.isModalVisible = true;
    },
    handleEdit(record) {
      this.isEditing = true;
      this.form = {...record};
      this.isModalVisible = true;
    },
    // handleChangeStatus(record) {
    //   record.status = record.status === '启用' ? '禁用' : '启用';
    // },
    handleDelete(record) {
      const index = this.data.findIndex(item => item.id === record.id);
      if (index !== -1) {
        this.data.splice(index, 1);
        this.handlePageChange(this.currentPage);
        console.log('删除成功');
      }
    },
    handleSave() {
      if (this.isEditing == false) {
        this.insertData(this.form.username, this.form.password)
      } else {
        const newAdmin = {...this.form, id: Date.now()}; // 使用当前时间戳作为ID
        this.data.push(newAdmin);
      }
      this.isModalVisible = false;
    },
    handleCancel() {
      this.isModalVisible = false;
    },
    async fetchData() {
      try {
        // 调用后端 API 获取用户信息
        const response = await request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/admin/infoAll`,
            METHOD.GET
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        );

        let adminData = response.data.data;
        // 遍历订单数据，设置 username
        adminData.forEach(item => {
          item.nickname = item.nickname == null || item.nickname === "" ? "乐购管理员": item.nickname;
          item.avatar = item.avatar == null || item.avatar === "" ? `${window.location.protocol}//${window.location.hostname}:8080/api/uploads/default_avatar.png` : item.avatar;
        });
        this.data = response.data.data;
      } catch (error) {
        console.error(error);
      }
    },
    async insertData(username, password) {
      try {
        // 调用后端 API 获取用户信息
        const response = await request(
            `${window.location.protocol}//${window.location.hostname}:8080/api/admin/register`,
            METHOD.POST,
            {
              username: username,
              password: password,
            }
            , {
              headers: {
                Accept: 'application/json',
                Authorization: `Bearer ` + localStorage.getItem("token")
              }
            }
        );
        console.log(response)
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

<style scoped>
/* 在这里可以添加样式 */
</style>
